package dao

import (
	kinit "longblog/work/base/initialize"

	kcommon "longblog/framework/tools/common"

	jgorm "github.com/jinzhu/gorm"
)

var ObjTest Test

type Test struct {
	ID        int64  `gorm:"primary_key" json:"-"`
	Title     string `gorm:"column:title" json:"title"`
	Content   string `gorm:"column:content" json:"content"`
	Status    int64  `gorm:"column:status" json:"status"`
	SortNum   int64  `gorm:"column:sort_num" json:"sort_num"`
	CreatedAt string `gorm:"column:created_at" json:"created_at"`
	UpdatedAt string `gorm:"column:updated_at" json:"updated_at"`
}

func (Test) TableName() string {
	return "test"
}
func (Test) Insert(tx *jgorm.DB, title string, content string, status int64) (Test, error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	tm := kcommon.TimestampToDateTime(kcommon.GetTimes())
	obj := Test{
		Title:     title,
		Content:   content,
		Status:    status,
		SortNum:   0,
		CreatedAt: tm,
		UpdatedAt: tm,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func (Test) GetById(tx *jgorm.DB, id int64) Test {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs Test
	tx.Where("id=? ", id).First(&objs)
	return objs
}

func (Test) GetByStatus(tx *jgorm.DB, status int64) []Test {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []Test
	tx.Where("status=? ", status).Find(&objs)
	return objs
}

func (Test) GetAll(tx *jgorm.DB) []Test {
	if tx == nil {
		tx = kinit.Gorm
	}
	var objs []Test
	tx.Find(&objs)
	return objs
}

func (Test) UpdateMById(tx *jgorm.DB, id int64, m map[string]interface{}) error {
	if tx == nil {
		tx = kinit.Gorm
	}

	if err := tx.Model(Test{}).Where("id=?", id).Updates(m).Error; err != nil {
		kinit.LogError.Println(err)
		return err
	}
	return nil
}
